package cn.leida.ruoyi.system.service.impl;

import cn.leida.ruoyi.common.constant.UserConstants;
import cn.leida.ruoyi.common.core.page.TableSupport;
import cn.leida.ruoyi.common.exception.CustomException;
import cn.leida.ruoyi.common.utils.StringUtils;
import cn.leida.ruoyi.common.utils.code.BusinessBizCode;
import cn.leida.ruoyi.system.dao.SysPostDao;
import cn.leida.ruoyi.system.dao.SysUserPostDao;
import cn.leida.ruoyi.system.domain.SysPost;
import cn.leida.ruoyi.system.service.ISysPostService;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Predicate;
import jakarta.persistence.criteria.Root;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 岗位信息 服务层处理
 *
 * @author liutietou
 * @since 1.0  2020-12-12
 */
@Transactional(readOnly = true)
@Service
public class SysPostServiceImpl  implements ISysPostService {

    @Autowired
    private SysPostDao postDao;

    @Autowired
    private SysUserPostDao userPostDao;

    /**
     * 查询岗位信息集合
     *
     * @param req 岗位信息
     * @return 岗位信息集合
     */
    @Override
    public Page<SysPost> selectPostList(SysPost req) {
        Specification<SysPost> example = new Specification<SysPost>() {
            private static final long serialVersionUID = 1L;

            @Override
            public Predicate toPredicate(Root<SysPost> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<>();
                if (StringUtils.isNoneBlank(req.getPostCode())) {
                    Predicate pre = cb.like(root.get("postCode").as(String.class), "%" + req.getPostCode() + "%");
                    list.add(pre);
                }
                if (StringUtils.isNoneBlank(req.getPostName())) {
                    Predicate pre = cb.like(root.get("postName").as(String.class), "%" + req.getPostName() + "%");
                    list.add(pre);
                }
                if (StringUtils.isNoneBlank(req.getStatus())) {
                    Predicate pre = cb.equal(root.get("status").as(String.class), req.getStatus());
                    list.add(pre);
                }
                if (list.isEmpty()) {
                    return null;
                }
                return cb.and(list.toArray(new Predicate[0]));
            }
        };
        return postDao.findAll(example, TableSupport.pageSort("postSort"));
    }

    /**
     * 查询所有岗位
     *
     * @return 岗位列表
     */
    @Override
    public List<SysPost> selectPostAll() {
        return postDao.findAll();
    }

    /**
     * 通过岗位ID查询岗位信息
     *
     * @param postId 岗位ID
     * @return 角色对象信息
     */
    @Override
    public SysPost selectPostById(Long postId) {
        return postDao.findById(postId).orElse(new SysPost());
    }

    /**
     * 根据用户ID获取岗位选择框列表
     *
     * @param userId 用户ID
     * @return 选中岗位ID列表
     */
    @Override
    public List<Long> selectPostListByUserId(Long userId) {
        return postDao.findPostListByUserId(userId);
    }

    /**
     * 校验岗位名称是否唯一
     *
     * @param post 岗位信息
     * @return 结果
     */
    @Override
    public boolean checkPostNameUnique(SysPost post) {
        Long postId = StringUtils.isNull(post.getPostId()) ? -1L : post.getPostId();
        List<SysPost> posts = postDao.findByPostName(post.getPostName());
        if (!posts.isEmpty() && posts.get(0).getPostId().longValue() != postId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验岗位编码是否唯一
     *
     * @param post 岗位信息
     * @return 结果
     */
    @Override
    public boolean checkPostCodeUnique(SysPost post) {
        Long postId = StringUtils.isNull(post.getPostId()) ? -1L : post.getPostId();
        List<SysPost> posts = postDao.findByPostCode(post.getPostName());
        if (!posts.isEmpty() && posts.get(0).getPostId().longValue() != postId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 通过岗位ID查询岗位使用数量
     *
     * @param postId 岗位ID
     * @return 结果
     */
    @Override
    public int countUserPostById(Long postId) {
        return userPostDao.countUserPostById(postId);
    }

    /**
     * 删除岗位信息
     *
     * @param postId 岗位ID
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deletePostById(Long postId) {
        postDao.deleteById(postId);
        return BusinessBizCode.OPTION_SUCCESS.getCode();
    }

    /**
     * 批量删除岗位信息
     *
     * @param postIds 需要删除的岗位ID
     * @return 结果
     * @throws Exception 异常
     */
    @Transactional(readOnly = false, rollbackFor = Exception.class)
    @Override
    public int deletePostByIds(Long[] postIds) {
        for (Long postId : postIds) {
            SysPost post = selectPostById(postId);
            if (countUserPostById(postId) > 0) {
                throw new CustomException(String.format("%1$s已分配,不能删除", post.getPostName()));
            }
        }
        postDao.deleteByPostIdIn(Arrays.asList(postIds));
        return BusinessBizCode.OPTION_SUCCESS.getCode();
    }

    /**
     * 新增保存岗位信息
     *
     * @param post 岗位信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertPost(SysPost post) {
        post.initCreateTime();
        postDao.save(post);
        return BusinessBizCode.OPTION_SUCCESS.getCode();
    }

    /**
     * 修改保存岗位信息
     *
     * @param post 岗位信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updatePost(SysPost post) {
        postDao.save(post);
        return BusinessBizCode.OPTION_SUCCESS.getCode();
    }
}
